import React from 'react';
import { connect } from 'dva'
import moment from 'moment'
import Tools from 'utils/tools'

import { Table } from 'antd';

import MyDatePicker from 'components/MyDatePicker'
import Title from 'components/Title'

import style from './style/reportTable.less'

import { config } from 'utils';
const { scada } = config;
const {
  Token,
  DdToken,
  Interval,
  IntervalMonth,
  StationIds,
} = scada;

const format = 'YYYY-MM-DD';
const nowTimeStamp = Date.now();
const now = new Date(nowTimeStamp);
const time = moment(now).format('YYYY')

@connect(({ business }) => ({ ...business }))
class reportTable extends React.Component {
    columns = [
        { title: '日期', dataIndex: 'time'},
        { dataIndex: 'waterSupply', title: '供水量（m³）' },
        { dataIndex: 'waterSell', title: '售水量（m³）' },
        { dataIndex: 'paidAmount', title: '已收水费（元）'},
        { dataIndex: 'waterSubtract', title: '产销差（m³）' },
        { dataIndex: 'waterSubtractRadio', title: '产销差率（%）' },
        { title: '抄表块数（个）', dataIndex: 'DivisionCopy'},
        { title: '抄见率（%）', dataIndex: 'DivisionCopyRadio' },
    ];
    List = [
      {
        title: '供水量',
        dataResource: 'SupplyWaterResourceReportList',
        server: {
          type: 'business/querySupplyWater', payload: { type: 'ReportList' }
        },
      },
      {
        title: '售水量',
        dataResource: 'SellWaterResourceReportList',
        server: {
          type: 'business/querySellWater', payload: { type: 'ReportList' }
        },
      },
      {
        title: '已收水费',
        server: {
          type: 'business/queryIncomingModel', payload: { type: 'ReportList', ids: "" }
        },
      },
      {
        title: '抄表块数', dataResource: 'DivisionCopyrateResourceReportList',
        server: {
          type: 'business/queryDivisionCopyrate', payload: { type: 'ReportList' }
        },
      },
    ]

  constructor(props) {
    super(props);

    this.state = {
        time,
        monthList: [],
    }
  }

  componentDidMount() {
    this.init()
  }

  init = async () => {
    this.setDateMonthList()
  }

  setDateMonthList = () => {
    const { time } = this.state;
    const monthList = Tools.getFullMonth(time);
    this.setState({
      monthList
    }, () => {
      this.setDateECharts()
    })
  }
  
  // 获取指标
  setDateECharts = async () => {
    const { List } = this;
    List.map(ele => {
      const { server } = ele;
      if (server) this.queryServer(server);
    })
  }

  queryServer = async (server) => {
    const { monthList } = this.state;

    const { type, payload } = server;
    const { type: unType } = payload;

    let payloads = {};
    let servers = {};
    // 供水量
    if(type === 'business/querySupplyWater'){
      monthList.map((ele,idx) =>{
        Object.assign(payloads, payload,{
          Token,
          Interval,
          StationId: StationIds.supply.join(','),
          Begin: moment(ele).startOf('month').unix(),
          End: moment(ele).endOf('month').unix(),
          type: `${unType}${idx}`
        })
        Object.assign(servers, server, { payload: payloads })
        this.props.dispatch(servers);
      });
    }else if(type === 'business/queryDivisionCopyrate'){
        monthList.map((ele,idx) =>{
            Object.assign(payloads, payload, {
                Token: DdToken,
                interval: IntervalMonth,
                begin: moment(ele).startOf('month').unix(),
                end: moment(ele).endOf('month').unix(),
                type: `${unType}${idx}`
            })
            Object.assign(servers, server, { payload: payloads })
            this.props.dispatch(servers);
        })
    }else{
      // 售水
      monthList.map((ele,idx) =>{
        // 售水量
        Object.assign(payloads, payload, {
          startDate: moment(ele).startOf('month').format(format),
          endDate: moment(ele).endOf('month').format(format),
          type: `${unType}${idx}`
        })
        Object.assign(servers, server, { payload: payloads })
        this.props.dispatch(servers);
      })
    }
  }

  // change
  handleChange = (data) => {
    console.log(data, 105)
    const lastTime = this.state.time;
    const time = moment(data).format('YYYY')
    if (lastTime === time) {
      return;
    }
    this.setState({
      time
    }, () => {
      this.init()
    })
  }

  getData = () => {
    const { state, props } = this;
    const { monthList } = state;

    let resource = []

      monthList.map((ele,idx) =>{
        // 售水累加
        const waterSell = Tools.countSellWater(props[`SellWaterResourceReportList${idx}`])
        // 供水量
        const waterSupply = Tools.countSupplyWater(props[`SupplyWaterResourceReportList${idx}`])
        // 已收水费
        const paidAmount = Tools.countSumPay(props[`IncomingResourceReportList${idx}`]);
        // 产销差
        const waterSubtract = waterSupply - waterSell;
        // 产销差率
        const waterSubtractRadio = waterSupply === 0 ? 0 : (waterSubtract / waterSupply * 100).toFixed(2);
        // 抄见率
        let DivisionCopy = 0;
        let DivisionCopyRadio = 0;
        if(props[`DivisionCopyrateResourceReportList${idx}`]){
            const copyResource = props[`DivisionCopyrateResourceReportList${idx}`];
            DivisionCopy = copyResource.succ
            DivisionCopyRadio = copyResource.copyRate
        }
        resource.push({ waterSupply, waterSell, waterSubtract, waterSubtractRadio, paidAmount, DivisionCopy, DivisionCopyRadio, time: moment(ele).format('YYYY-MM') })
      })
    return resource;
  }
// 隔行换色
setRowClassName = (record, index) => {
    const doubleRow = style.doubleRow;
    if (index % 2 !== 0) {
      return doubleRow;
    }
  };
  // 供水量 - 售水量 - 产销差 - 产销差率 - 已收消费 计算逻辑
  render() {
    let { columns } = this;
    const dataSource = this.getData();
  return (<>
      <MyDatePicker
        defaultValue={time}
        onChange={this.handleChange}
      />
      <Title title={'重点指标监控'} style={{ paddingLeft: '4%', paddingRight: '4%' }}>
      <Table
        columns={columns}
        dataSource={dataSource}
        size={'small'}
        pagination={{ pageSize: 12 }}
        rowClassName={this.setRowClassName}
        bordered
      />
        </Title>
    </>)
  }
}

export default reportTable;
